<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="分类名称:" prop="categoryName">
        <el-input v-model="queryParams.categoryName" size="small" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否显示:" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择是否显示" clearable size="small">
          <el-option v-for="option in options.sysYnTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['goods:category:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['goods:category:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['goods:category:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" row-key="id" :data="categoryList" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="分类编码" align="center" prop="id" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <!--<el-table-column label="级别" align="center" prop="treeLevel" />-->
      <!--<el-table-column label="模板" align="center" prop="templateName" />-->
      <el-table-column label="商品数量" align="center" prop="goodsNum" />
      <!--<el-table-column label="是否显示" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isShow" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>-->
      <el-table-column label="排序" align="center" prop="treeSort" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['goods:category:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['goods:category:insert']" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button v-hasPermission="['goods:category:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="categoryFormDialog.title" :visible.sync="categoryFormDialog.visible" :close-on-click-modal="false" :before-close="resetCategoryFormDialog" width="600px" append-to-body>
      <el-form ref="categoryForm" :model="categoryFormData" :rules="categoryFormRules" label-width="80px">
        <el-row :span="24">
          <el-col>
            <el-form-item label="上级分类" prop="pid">
              <treeselect v-model="categoryFormData.pid" :options="options.categoryOptions" :normalizer="normalizer" placeholder="选择上级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编码" prop="id">
              <el-input v-model="categoryFormData.id" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="categoryFormData.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <!--<el-col :span="12">
            <el-form-item label="模板" prop="templateId">
              <el-select v-model="categoryFormData.templateId" filterable clearable placeholder="请选择模板">
                <el-option v-for="option in options.specParamTemplateOptions" :key="option.id" :label="option.templateName" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>-->
          <!--<el-col :span="12">
            <el-form-item label="是否显示" prop="isShow">
              <el-radio-group v-model="categoryFormData.isShow">
                <el-radio v-for="option in options.sysYnTypeOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>-->
          <!--<el-col :span="12">
            <el-form-item label="级别">
              <el-input v-model="categoryFormData.treeLevel" placeholder="请输入级别" />
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="排序" prop="treeSort">
              <el-input v-model="categoryFormData.treeSort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品数量">
              <el-input v-model="categoryFormData.goodsNum" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmCategoryFormDialog">确 定</el-button>
        <el-button @click="resetCategoryFormDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CategoryApi from '@/api/goods/CategoryApi'
import DictValueApi from '@/api/system/DictValueApi'
import SpecParamTemplateApi from '@/api/goods/SpecParamTemplateApi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const defaultCategoryFormData = {
  id: null,
  pid: '0',
  categoryName: null,
  templateId: null,
  isShow: '1',
  goodsNum: 0,
  treeLevel: 1,
  treeSort: 10
}
export default {
  name: 'CategoryList',
  components: { Treeselect },
  data() {
    return {
      options: {
        categoryOptions: [],
        specParamTemplateOptions: [],
        sysYnTypeOptions: []
      },
      queryParams: {
        categoryName: null,
        isShow: null,
        isValid: this.$constant.Y
      },
      categoryList: [],
      categoryFormDialog: {
        title: '',
        visible: false,
        type: null
      },
      categoryFormData: Object.assign({}, defaultCategoryFormData),
      categoryFormRules: {
        id: [{ required: true, message: '分类编码不能为空', trigger: 'blur' }],
        categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
      },
      loading: true,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_yn_type' }).then(response => {
        this.options.sysYnTypeOptions = response.data
      })
      SpecParamTemplateApi.list().then(response => {
        this.options.specParamTemplateOptions = response.data
      })
    },
    handleAdd(row) {
      this.categoryFormDialog.type = 'add'
      this.openCategoryFormDialog(row.id)
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return CategoryApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      this.categoryFormDialog.type = 'edit'
      this.openCategoryFormDialog(row.id)
    },
    handleQuery() {
      this.loading = true
      CategoryApi.list(this.queryParams).then(response => {
        this.categoryList = this.$common.list2Tree(response.data)
        this.loading = false
      }, () => {
        this.loading = false
      })
      CategoryApi.treeSelect().then(response => {
        const root = { id: 0, label: '主类目', children: [] }
        root.children = response.data
        this.options.categoryOptions.push(root)
      })
    },
    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return CategoryApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    handleStatusChange(row) {
      const display = row.isShow === '0' ? '隐藏' : '显示'
      this.$confirm('确认要"' + display + '"分类吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return CategoryApi.edit({ id: row.id, isShow: row.isShow })
      }).then(() => {
        this.$message.success(display + '成功')
        this.handleQuery()
      }).catch(function() {
        row.isShow = row.isShow === '0' ? '1' : '0'
      })
    },
    openCategoryFormDialog(id) {
      this.categoryFormDialog.visible = true
      if (this.categoryFormDialog.type === 'add') {
        this.categoryFormDialog.title = '分类-添加'
        if (id) {
          this.categoryFormData.pid = id
        } else {
          this.categoryFormData.pid = 0
        }
      }
      if (this.categoryFormDialog.type === 'edit') {
        this.categoryFormDialog.title = '分类-修改'
        CategoryApi.get(id).then(response => {
          this.categoryFormData = response.data
        })
      }
    },
    confirmCategoryFormDialog() {
      this.$refs['categoryForm'].validate(valid => {
        if (valid) {
          if (this.categoryFormDialog.type === 'add') {
            CategoryApi.add(this.categoryFormData).then(response => {
              this.$message.success('添加成功')
              this.resetCategoryFormDialog()
              this.handleQuery()
            })
          }
          if (this.categoryFormDialog.type === 'edit') {
            CategoryApi.edit(this.categoryFormData).then(response => {
              this.$message.success('修改成功')
              this.resetCategoryFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetCategoryFormDialog() {
      this.categoryFormDialog = {
        title: '',
        visible: false,
        type: null
      }
      this.categoryFormData = Object.assign({}, defaultCategoryFormData)
      this.resetForm('categoryForm')
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return node
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
